<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\Api\Integrals as IntegralCollection;
use App\Models\Integral;
use App\Models\IntegralUser;
use Illuminate\Http\Request;

class IntegralsController extends Controller
{

    // 获取列表
    public function index(Request $request)
    {
        $userId = app('auth')->id();
        $integrals = Integral::with([
            'user' => function ($query) use ($userId) {
                $query->where('user_id', $userId);
            },
        ])->get();
        return new IntegralCollection($integrals);
    }

    // 进入巡回赛
    public function play(Request $request, $id)
    {
        $integral = Integral::findOrFail($id);
        $userId = app('auth')->id();

        // 验证巡回赛是否已解锁
        $integralUser = IntegralUser::where([
            'user_id' => $userId,
            'integral_id' => $integral->id,
        ])->first();
        $firstIntegral = Integral::orderBy('id', 'ASC')->first();
        $isUnlock = false;
        if (
            $firstIntegral->id == $integral->id ||
            ($integralUser && $integralUser->prize_count >= $integral->upgrade_need)
        ) {
            $isUnlock = true;
        }

        if (!$isUnlock) {
            return invalidation('this integral is locked');
        }

        // 生成用户巡回赛数据
        $integralUser = IntegralUser::updateOrCreate([
            'user_id' => $userId,
            'integral_id' => $integral->id,
        ],
            [
                'status' => IntegralUser::STATUS_NORMAL,
            ]);

        // 返回数据
        return [
            //自动匹配后客户端进入该链接（游戏已开始，等待进入）
            'ws_url' => 'ws://' . get_server_addr() . '/integral/' . $integral->id . '?uid=' . $userId,
        ];
    }

    // 获取正在进行的游戏
    public function check()
    {
        $userId = app('auth')->id();

        $integral = Integral::join('integral_users', 'integral_users.integral_id', '=', 'integrals.id')
            ->where('integral_users.user_id', $userId)
            ->whereRaw('integral_users.status <> 0')
            ->first();
        if ($integral) {
            return $integral->toArray() + [
                'ws_url' => 'ws://' . get_server_addr() . '/integral/' . $integral->id . '?uid=' . $userId,
            ];
        }
        return [];

    }
}
